import { Component, EventEmitter, Input, OnDestroy, OnInit, Output, TemplateRef, ViewChild } from '@angular/core';
import { STColumn, STColumnButton, STComponent, STData, STPage, STReq, STStatisticalResults } from '@delon/abc';
import { AreaService } from '../../../routes/sys-setting/area-manage/area.service';
import { SFComponent } from '@delon/form';
import { UtilService } from '@core/services/util.service';
export interface SPage {
  columns: Array<{
    index: string,
    title: string,
    fFn?: (item, columu) => string,
    clickFn?:(item, columu) => void,
    type?: ColumnType,
    className?: string,
    filter?: {
      type: string,
      hideSearch?: boolean,
      defatuts?: any,
      format?:string,
      placeholder?: string,
      mode?: string,
      index?: string, // 检索字段 当检索字段和列表字段不一致时用
      items?: Array<{label, value}>,
      change?: (value, orgData) => void,
    }
    [key: string]: any
  }>,
  editBtn?: Array<{
    title: string,
    type?: string,
    iif?: (item: STData, btn?: STColumnButton, column?: STColumn) => boolean
  }>
  ps?: number,
  showCheckBox?: boolean,
  hideSearch?: boolean,
  reqUrl?: string,
  data?: Array<object>,
  exportFile? : {url: string}
  defaultParam?: object
}
export enum ColumnType {
  no= 'no',
  checkbox= 'checkbox',
  radio = 'radio',
  link = 'link',
  img = 'img',
  number = 'number',
  currency = 'currency',
  date = 'date',
  badge = 'badge',
  tag = 'tag'
}
@Component({
  selector: 'app-table-page',
  templateUrl: './table-page.component.html',
  styleUrls: ["./table-page.css"]
})
export class TablePageComponent implements OnInit, OnDestroy {
  @ViewChild('st', {static: false})st: STComponent;
  @ViewChild('sf', {static: false})sf: SFComponent;
  @Output()_selectChange = new EventEmitter();
  @Output()operateClick = new EventEmitter();
  @Input()tmp: TemplateRef<void>;
  @Input()bodyTpl: TemplateRef<void>;
  @Input()btnTmp: TemplateRef<void>;//自定义的搜索条件按钮
  @Input()flag = true; // 是否显示搜索和重置按钮
  @Input()process: (data: STData, rawData?: any) => STData[];
  @Input()
  set config(value: SPage) {
    this._config = value;
    this.stConfig = value.columns.map(item => {
      if (item.filter) {
        if (!item.filter.hideSearch) {
          this.showSearch = true;
          this.searchSchema.properties[item.filter.index || item.index] = {
            type: 'string',
            format: item.filter.mode,
            title:  ''
          }
          if (item.filter.defatuts) {
            this.formData[item.filter.index || item.index] = item.filter.defatuts;
          }
          this.searchSchema.properties[item.filter.index || item.index].ui = {
            widget: item.filter.type,
            placeholder: item.filter.placeholder || item.title,
            mode: item.filter.mode,
            format:item.filter.format,
            allowClear: true,
            width: 200,
            change:item.filter.change
          }
          if (item.filter.items) {
            this.searchSchema.properties[item.filter.index || item.index].enum = item.filter.items;
          }
        }
      }
      if (item.fFn) {
        item.format = item.fFn;
      }
      const {filter, ...obj} = item;
      if (item.filter && item.filter.items && item.type !== ColumnType.badge &&item.type !== ColumnType.tag) {
        obj.format = (data, col) => {
          const res =  item.filter.items.find(_value => String(_value.value) === String(data[col.indexKey]));
          return res ? res.label : '-'
        }
      }
      return obj;
    })
    if (value.editBtn && value.editBtn.length > 0) {
      let btns;
      btns = value.editBtn.map(item => {
        return {
          text: item.title,
          type: item.type || 'none',
          iif: item.iif,
          click: (data) => {
            this.operateClick.emit({title: item.title, data});
          }
        }
      })
      this.stConfig.push({
        title: '操作',
         buttons: btns
      })
    }
  }
  formData: any = {};
  _config: SPage;
  stConfig: STColumn[];
  //分页配置
  pageConfig:STPage = {
    placement : 'left',
    showQuickJumper : true,
    showSize: true,
    pageSizes : [10,20,30,40,50],
  };
  location$;
  searchSchema = {
    properties: {}
  };
  showSearch = false;
  arr = []
  searchData(e): void {
    if(this.flag === true){
      if(e != null){
        console.log(e)
        let data:any=this.util.getStorage("userNow");
        data=JSON.parse(data);
        Object.keys(e).forEach(item=>{
          if(Array.isArray(e[item])){
            if(e[item].length != 0){
              e[item]=data.id;
            }else{
              delete e[item];
            }
          }else{
            let str = e[item]+"".trim()
            if(str.length == 0){
              delete e[item]
            }
          }
        })
      }
      this.st.reset({...this._config.defaultParam, ...e})
    }
  }
  selectChange(e): void {
    if (e && e.type === 'checkbox') {
      this._selectChange.emit(e.checkbox);
    }
    if (e && e.type === 'radio') {
      this._selectChange.emit(e.radio);
    }
  }
  reload(): void {
    if(this.flag === true){
      this.searchData(null);
    }
  }
  exportFile(): void {

  }
  constructor(
    private area: AreaService,
    private util:UtilService
  ) { }

  ngOnInit() {
    this.location$ = this.area.getLocation().subscribe(res => {
      this.reload();
    });
  }
  ngOnDestroy() {
    this.location$.unsubscribe();
  }
}
